package com.bxshey.happyTown.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Slf4j
public class UploadTheFile {

    private static final String HTTP = "http://www.lyzhnb.top/"; //oss存储域名
    private static final String ACCESS_KEY = "QbGiNW7Hmi2BeXUaM86wfCQ_MXRYd3jYlQOo50Ga" ;  //七牛云的accessKey
    private static final String SECRET_KEY = "CVf6HvfIBLDFXIH3VCUMFG8FUpfP8XgQryWNMEah";   //七牛云的secretKey
    private static final String BUCKET = "lyzhnb-blog"; //仓库名


    /**
     * 上传图片文件  单个 或 多个
     */
    public List<String> uploadFile(MultipartFile[] file,List<String> key) {
//构造一个带指定 Region 对象的配置类 Region.region2() 意思是你的仓库是哪个地区的 例如 华南或华北等。。
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
//默认不指定key的情况下，以文件内容的hash值作为文件名
        List<String> path = new ArrayList<>();
        // 循环遍历的效果
        for (int i=0;i<file.length;i++) {
            try {
                byte[] uploadBytes = file[i].getBytes();
                ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
                Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
                String upToken = auth.uploadToken(BUCKET);
                try {
                    Response response = uploadManager.put(byteInputStream, key.get(i), upToken, null, null);
                    //解析上传成功的结果
                    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                    path.add(HTTP + putRet.key);
                } catch (QiniuException ex) {
                    Response r = ex.response;
                    log.warn("{} 上传对象存储图片失败: {}",path,ex);
                }
            } catch (IOException ex) {
                //ignore 忽视
            }
        }
        return path; //返回路径交由前端
    }

    /**
     * 删除图片文件  单个 或 多个
     * pat 要删除的图片名
     */
    public Integer deleteFile(String[] path) {
        //构造一个带指定 Region 对象的配置类，指定七牛云的存储位置
        Configuration cfg = new Configuration(Region.region0());
        //设置密钥信息
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);
           int count=0;
            try {
                //单次批量请求的文件数量不得超过1000
                BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
                batchOperations.addDeleteOp(BUCKET, path);
                Response response = bucketManager.batch(batchOperations);
                BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
                for (int i = 0; i < path.length; i++) {
                    BatchStatus status = batchStatusList[i];
                    String key = path[i];
                    //删除成功或失败提示信息
                    if (status.code == 200) {
                        count++;
                    }else {
                        log.warn("删除对象存储图片失败: {} -> {} ",status.data.error,key);
                    }
                }
            } catch (QiniuException ex) {
                log.warn(ex.response.toString());
            }
        return count > 0 ? count : null;
    }

    //检测上传文件类型
    public static boolean fileFormat(MultipartFile[] file){
        if(file.length<20)
            return false;
        String[] type = {"jpg","png","gif","jpeg","svg"};
        boolean value = false;
        for (MultipartFile files : file) {
            //判断格式是否正确
            for(String str : type) {
                if (str.equalsIgnoreCase(StringUtils.substringAfterLast(files.getOriginalFilename(), "."))) {
                    value = true;
                    break;
                }
            }
            if(value)
                return true;
        }
        return false;
    }


    // 截取字符串从传入的 c值 开始
    public static String[] intercept(String[] path,String c){
        for (int i=0;i<path.length;i++)
            if (path[i].contains(c)){
                 path[i] = StringUtils.substringAfterLast(path[i], c);
            }
        return path;
    }


}




